package com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.service;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.coderfid;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.entity.storeRecord;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.mapper.CoderfidMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.RFIDCodeDetail.service.RfidCodeDetailService;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.guize.mapper.GuiZeMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.Location;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.OrderNoticeEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.LocationMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.mapper.StockMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.model.CoderfidBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.model.ProductInfoBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.stock.model.productInfo;
import com.yonyou.ucf.mdf.app.isvdxq.other.service.BaseService;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.entity.TaglistEntity;
import com.yonyou.ucf.mdf.app.isvdxq.secondpart.service.TaglistService;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StockService {
    @Autowired
    CoderfidMapperImpl coderfidMappersel;
    @Autowired
    StockMapperImpl stockMapper;
    @Autowired
    LocationMapperImpl locationMapper;
    @Autowired
    GuiZeMapperImpl guiZeMapper;
    @Autowired
    RfidCodeDetailService rfidCodeDetailService;
    @Autowired
    BaseService baseService;
    @Autowired
    TaglistService taglistService;

    /**
     * 根据RfidCode 获取货品信息
     * 单条扫描 目的验证物料是否合法
     *
     * @param rfidCode RfidCode
     * @param orderId  单据id
     * @return 返回货品信息列表
     */
    public DataResult GetGoodsByLabelCode(List<String> rfidCode, String orderId, String ordertype, List<String> warehouseIds, String tenantId) {
        DataResult dataResult = new DataResult(0, "标签未被使用");
        // 单据是否弃审的检查
        if (StringUtils.isNotEmpty(orderId) && StringUtils.isNotEmpty(ordertype)) {
            OrderNoticeEntity ordernotice = guiZeMapper.selectOrderNoticeByIdAndType(orderId, ordertype);
            if (ordernotice != null) {
                dataResult.setOrderAuditType(ordernotice.getAuditstatus());
            }
        }
        List<ProductInfoBean> rfidCodeList = new ArrayList<>();
        try {
            if (rfidCode == null || rfidCode.size() == 0) return dataResult;
            rfidCodeList = stockMapper.selectByRfidCode(rfidCode, warehouseIds, tenantId);
            if (rfidCodeList == null || rfidCodeList.size() == 0) return dataResult;
            // 获取标签出库记录信息
            List<String> ids_EPC = rfidCodeList.stream().map(it -> it.getId()).distinct().collect(Collectors.toList());
            List<storeRecord> storeRecordList = new ArrayList<>();
            if (ids_EPC.size() > 0) {
                storeRecordList = stockMapper.selectstoreRecordByRfid(ids_EPC, tenantId);
            }
            for (ProductInfoBean item : rfidCodeList) {
                if (storeRecordList != null && storeRecordList.size() > 0) {
                    storeRecord storerecode = storeRecordList.stream()
                            .filter(it -> it.getRfidcodeId().equals(item.getId()))
                            .findAny().orElse(null);
                    if (storerecode != null) {
                        item.setOrdercode(storerecode.getOrdercode());
                        item.setOrdertype(storerecode.getOrdertype());
                        item.setBatch_no(storerecode.getBatch_no());
                    }
                }
                // 补全货位信息
                List<Location> allLocationList = locationMapper.getLocationByWarehouseId(item.getWarehouse_id(),
                        tenantId);
                String locationName = rfidCodeDetailService.getLocationNamesel(item.getLocation_id(),
                        allLocationList, "");
                item.setPathName(locationName);
            }

            dataResult.setStatus(1);
            dataResult.setMessage("查询成功");
            dataResult.setData(rfidCodeList);
            return dataResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResult;
    }

    /**
     * 检测标签是否出库合法 bychen 基于一期修改
     *
     * @param rfidCode
     * @param orderId
     * @param tenantId
     * @return
     */
    public DataResult CheckGoodsByLabelCode(List<String> rfidCode, String orderId, String ordertype, List<String> warehouseIds, String tenantId) {
        DataResult dataResult = new DataResult(0, "标签未被使用");
        // 单据是否弃审的检查
        if (StringUtils.isNotEmpty(orderId)) {
            OrderNoticeEntity ordernotice = guiZeMapper.selectOrderNoticeByIdAndType(orderId, ordertype);
            if (ordernotice != null) {
                dataResult.setOrderAuditType(ordernotice.getAuditstatus());
            }
        }

        List<ProductInfoBean> rfidCodeList = new ArrayList<>();
        try {
            // 获取标签物料信息
            if (rfidCode == null || rfidCode.size() == 0) return dataResult;
            rfidCodeList = stockMapper.selectByRfidCode(rfidCode, warehouseIds, tenantId);
            if (rfidCodeList == null || rfidCodeList.size() == 0) return dataResult;
            // 检测仓库信息
            List<String> list_warehouseId = rfidCodeList.stream()
                    .map(it -> it.getWarehouse_id()).distinct()
                    .collect(Collectors.toList());
            if (list_warehouseId.size() != 1) {
                dataResult.setMessage("检测到混合仓库数据异常");
                return dataResult;
            }
            // 获取标签出库记录信息
            List<String> ids_EPC = rfidCodeList.stream().map(it -> it.getId()).collect(Collectors.toList());
            List<storeRecord> storeRecordList = new ArrayList<>();
            if (ids_EPC.size() > 0)
                storeRecordList = stockMapper.selectstoreRecordByRfid(ids_EPC, tenantId);

            for (ProductInfoBean item : rfidCodeList) {
                if (storeRecordList != null && storeRecordList.size() > 0) {
                    storeRecord storerecode = storeRecordList.stream()
                            .filter(it -> it.getRfidcodeId().equals(item.getId()))
                            .findAny().orElse(null);
                    // 发货补全信息
                    if (storerecode != null) {
                        item.setOrdercode(storerecode.getOrdercode());
                        item.setOrdertype(storerecode.getOrdertype());
                        item.setBatch_no(storerecode.getBatch_no());
                    }
                }
                // 补全货位信息
                List<Location> allLocationList = locationMapper.getLocationByWarehouseId(list_warehouseId.get(0),
                        tenantId);
                String locationName = rfidCodeDetailService.getLocationNamesel(item.getLocation_id(),
                        allLocationList, "");
                item.setPathName(locationName);
            }

            dataResult.setStatus(1);
            dataResult.setMessage("查询成功");
            dataResult.setData(rfidCodeList);
            return dataResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataResult;
    }

    /**
     * 根据Rfid标签获取分页的信息
     *
     * @param rfidCode 标签值
     * @param page     查询的页面
     * @param pageSize 页面条数
     * @return 返回根据页面和rfid标签查询的结果
     */
    public DataResult<productInfo> GetGoodsByLabelCodeAndPage(List<String> warehouseIds, String rfidCode, String productName,
                                                              int page, int pageSize, String trantid
    ) {
        List<productInfo> rfidCodeList = new ArrayList<>();
        DataResult<productInfo> dataResult = new DataResult<>(0, "暂无数据");
        try {
            int total = 0;
            if (StringUtils.isNotEmpty(rfidCode) && rfidCode.startsWith("B01")) {
                Location location = locationMapper.getLocationInfoByRfidCode(warehouseIds, rfidCode, trantid);
                if (location == null) {
                    return dataResult;
                }
                String locationId = "%" + location.getId() + "%";
                List<LocationEntity> locationRfidList = locationMapper.GetLocationListByPath(locationId, trantid);
                if (locationRfidList == null || locationRfidList.size() == 0) {
                    dataResult.setStatus(0);
                    dataResult.setMessage("该标签无法搜索到对应货位");
                    return dataResult;
                }
                List<String> locationRfidCode = locationRfidList.stream().filter(it -> StringUtils.isNotEmpty(it.getRfid_code()))
                        .map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
                rfidCodeList = stockMapper.selectByRfidCodeAndPageHuoWei(locationRfidCode, productName, page,
                        pageSize, trantid);
                total = stockMapper.selectByRfidCodeAndPageHuoWeiTotal(locationRfidCode, productName, trantid);

            } else {
                rfidCodeList = stockMapper.selectByRfidCodeAndPage(warehouseIds, rfidCode, productName, trantid, page
                        , pageSize);
                total = stockMapper.selectByRfidCodeAndPageTotal(warehouseIds, rfidCode, productName, trantid);
            }
            // 扩展托盘信息
            if (rfidCodeList != null && rfidCodeList.size() > 0) {
                List<String> strList = rfidCodeList.stream().filter(it -> it.getRfid_code() != null)
                        .map(it -> it.getRfid_code()).distinct().collect(Collectors.toList());
                List<TaglistEntity> taglistEntities = taglistService.SelectByEpcs(strList, trantid);
                for (productInfo item : rfidCodeList) {
                    List<Location> allLocationList = locationMapper.getLocationByWarehouseId(item.getWarehouse_id(), trantid);
                    String locationName = rfidCodeDetailService.getLocationNamesel(item.getLocation_id(), allLocationList, "");
                    item.setPathName(locationName);
                    TaglistEntity tagEntity = taglistEntities.stream().filter(it -> it.getCoderfid().equals(item.getRfid_code())).findFirst().orElse(null);
                    if (tagEntity != null) item.setPallet(tagEntity.getName());
                }
            }
            dataResult.setStatus(1);
            dataResult.setMessage("查询成功");
            dataResult.setPageParams(rfidCodeList, total);
        } catch (Exception ex) {
            dataResult.setMessage(ex.getMessage());
        }
        return dataResult;

    }

    /**
     * 拆合签 - 拆签合签
     * 一期拆签
     * 修改签 未处理记录
     *
     * @param rfidCode   目标实体
     * @param listEntity 合并实体
     * @param type       0拆签 1合签
     * @return
     */
    public DataResult LabelCodeSplit(String rfidCode, List<CoderfidBean> listEntity, int type, String tenantId) throws Exception {
        DataResult dataResult = new DataResult(0, "操作失败");
        if (listEntity == null || listEntity.size() == 0) return dataResult;
        if (type == 0) {
            coderfid myEntity = coderfidMappersel.getFRIDCode(rfidCode, tenantId);
            List<coderfid> addEntitys = new ArrayList<>();
            listEntity.forEach(itemObj -> {
                coderfid model = new coderfid();
                model = (coderfid) MyTool.convertBean2Bean(myEntity, model);
                model.setRfid_code(itemObj.getCode());
                model.setF_stock_count(itemObj.getCount().doubleValue());
                model.setF_move_count(Double.valueOf(0));
                model.setF_out_count(Double.valueOf(0));
                model.setSource_code(myEntity.getRfid_code());
                addEntitys.add(model);
            });
            //循环写入拆签数据
            for (coderfid CodeBind : addEntitys) {
                String id = MyTool.getRandomId();
                int rInt = coderfidMappersel.InsertCoderfid(CodeBind.getEpc_tid(), CodeBind.getRfid_code(),
                        CodeBind.getProduct_id(), CodeBind.getProduct_name(),
                        CodeBind.getProduct_sku_id(), CodeBind.getProduct_sku_name(), CodeBind.getUnitId(),
                        CodeBind.getUnit_name(),
                        CodeBind.getStockUnitId(), CodeBind.getStock_unit_name(), CodeBind.getF_stock_count(),
                        myEntity.getWarehouse_id(), myEntity.getWarehouse_code(), CodeBind.getTenant_id(),
                        CodeBind.getCreator(), CodeBind.getModifier(), id, CodeBind.getBatchno(),
                        CodeBind.getProductDate());
                if (rInt == 0) throw new RuntimeException("拆签写入数据异常");
            }
            //更新原签数据
            Double count = listEntity.stream().map(CoderfidBean::getCount).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue();
            Double stockcount = myEntity.getF_stock_count() - count;
            int resInt = coderfidMappersel.updateRFIDCode(rfidCode, stockcount, tenantId);
            if (resInt == 0) return dataResult;
            dataResult = new DataResult(1, "操作成功");
        } else if (type == 1) {
            dataResult = new DataResult(1, "暂不支持");
        }
        return dataResult;
    }
}
